package com.example.note;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.note.db.MyHelper;
import com.example.note.utils.DBUtils;

public class RecordActivity extends AppCompatActivity {
    private ImageView note_back, note_save, note_delete;
    private TextView note_time, noteName;
    private EditText content;
    private int id;
    private MyHelper myHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);
        note_back = findViewById(R.id.note_back);
        note_save = findViewById(R.id.note_save);
        note_delete = findViewById(R.id.delete);
        note_time = findViewById(R.id.tv_time);
        content = findViewById(R.id.note_content);
        noteName = findViewById(R.id.note_name);
        //给回退、删除、保存按钮注册监听
        note_back.setOnClickListener(view -> finish());
        note_save.setOnClickListener(view -> {
            //获取用户输入的内容
            String noteContent = content.getText().toString().trim();
            if (id >0) {//修改界面的数据
                if (!noteContent.isEmpty()) {
                    if (myHelper.updateData(id, noteContent, DBUtils.getTime())) {
                        showToast("修改成功");
                        setResult(2);
                        finish();
                    } else {
                        showToast("修改失败");
                    }
                } else {
                    showToast("修改内容不能为空");
                }
            } else {
                //向数据库中添加数据
                if (!noteContent.isEmpty()) {
                    if (myHelper.insertData(noteContent, DBUtils.getTime())) {
                        showToast("保存成功");
                        setResult(2);
                        finish();
                    } else {
                        showToast("保存失败");
                    }
                } else {
                    showToast("输入内容不能为空！");
                }
            }
        });
        note_delete.setOnClickListener(view -> content.setText(""));
        myHelper = new MyHelper(this);
        initData();
    }

    public void showToast(String message) {
        Toast.makeText(RecordActivity.this, message, Toast.LENGTH_SHORT).show();
    }

    public void initData() {
        Intent intent = getIntent();
        if (intent != null) {//将传来的内容初始化到界面上
            id = intent.getIntExtra("id", 0);
            if (id >0) {
                noteName.setText("修改记录");
                content.setText(intent.getStringExtra("content"));
                note_time.setText(intent.getStringExtra("notetime"));
                note_time.setVisibility(View.VISIBLE);
            }
        }
        noteName.setText("添加记录");
    }
}
